<template>
  <div class="signup-management-container">
    <el-card class="filter-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>活动报名管理</h3>
          <!-- <el-button type="primary" @click="handleSignUp">
            <el-icon><plus /></el-icon> 新增报名
          </el-button> -->
        </div>
      </template>
      
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="活动ID">
          <el-input v-model="searchForm.activityId" placeholder="请输入活动ID" clearable />
        </el-form-item>
        
        <!-- <el-form-item label="志愿者ID">
          <el-input v-model="searchForm.volunteerId" placeholder="请输入志愿者ID" clearable />
        </el-form-item> -->
        
        <el-form-item label="报名状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="已报名" value="1" />
            <el-option label="已签到" value="2" />
            <el-option label="已签退" value="3" />
            <el-option label="已评价" value="4" />
            <el-option label="已取消" value="5" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="table-card" shadow="hover">
      <el-table
        :data="signupList"
        border
        stripe
        highlight-current-row
        :row-key="row => row.id"
        @row-dblclick="handleEditSignup"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="activityName" label="活动" width="100" align="center" />
        <el-table-column prop="volunteerName" label="志愿者" width="100" align="center" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusName(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="signupTime" label="报名时间" min-width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.signupTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <!-- <el-button 
              type="primary" 
              size="small" 
              @click="handleEditSignup(row)"
              :disabled="row.status === 5"
            >
              <el-icon><edit /></el-icon> 编辑
            </el-button> -->
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDeleteSignup(row)"
              :disabled="row.status !== 1"
            >
              <el-icon><delete /></el-icon> 取消报名
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑报名对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑报名信息' : '新增报名'"
      width="40%"
    >
      <el-form 
        :model="formData" 
        :rules="rules" 
        ref="formRef" 
        label-width="120px"
      >
        <el-form-item label="活动ID" prop="activityId">
          <el-input v-model="formData.activityId" placeholder="请输入活动ID" />
        </el-form-item>
        
        <el-form-item label="志愿者ID" prop="volunteerId">
          <el-input v-model="formData.volunteerId" placeholder="请输入志愿者ID" />
        </el-form-item>
        
        <el-form-item label="报名状态" prop="status">
          <el-select 
            v-model="formData.status" 
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option label="已报名" value="1" />
            <el-option label="已签到" value="2" />
            <el-option label="已签退" value="3" />
            <el-option label="已取消" value="5" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveSignup">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认取消报名"
      width="30%"
    >
      <p>确定要取消报名 #{{ deleteSignupId }} 吗？</p>
      <p class="warning-text">此操作仅允许取消未签到的报名记录！</p>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue';
import { ElMessage } from 'element-plus';
import {
  Plus,
  Search,
  Refresh,
  Edit,
  Delete
} from '@element-plus/icons-vue';
import request from '@/utils/request';

// 搜索表单
const searchForm = reactive({
  activityId: '',
  volunteerId: '',
  status: ''
});

// 表格数据
const signupList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);

// 当前用户信息
const currentUser = ref(null);
const currentVolunteerId = ref(null);

// 对话框状态
const dialogVisible = ref(false);
const isEditMode = ref(false);
const formData = reactive({
  id: null,
  activityId: '',
  volunteerId: '',
  status: 1
});

// 表单验证规则
const rules = reactive({
  activityId: [
    { required: true, message: '请输入活动ID', trigger: 'blur' },
    { type: 'number', message: '请输入有效的活动ID', trigger: 'blur' }
  ],
  volunteerId: [
    { required: true, message: '请输入志愿者ID', trigger: 'blur' },
    { type: 'number', message: '请输入有效的志愿者ID', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择报名状态', trigger: 'change' }
  ]
});

// 删除对话框
const deleteDialogVisible = ref(false);
const deleteSignupId = ref(null);

// 表单引用
const formRef = ref(null);

// 生命周期钩子
onMounted(() => {
  initUserInfo();
});

// 初始化用户信息并获取志愿者ID
const initUserInfo = async () => {
  try {
    // 从localStorage获取当前用户信息
    const userInfo = localStorage.getItem('userInfo');
    if (userInfo) {
      currentUser.value = JSON.parse(userInfo);
      // 根据用户ID获取志愿者ID
      const response = await request.get(`/user-service/user/profile/getVolunteerId/${currentUser.value.id}`);
      if (response.code === 200) {
        currentVolunteerId.value = response.data;
        fetchSignupList(); // 获取志愿者ID后再加载报名列表
      } else {
        ElMessage.warning('未找到对应的志愿者信息');
      }
    } else {
      ElMessage.error('未登录，请先登录');
      // 跳转到登录页面
      // router.push('/login');
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败');
    console.error('获取用户信息错误:', error);
  }
};

// 获取报名列表
const fetchSignupList = async () => {
  if (!currentVolunteerId.value) return; // 确保有志愿者ID
  
  loading.value = true;
  
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      activityId: searchForm.activityId || undefined,
      volunteerId: currentVolunteerId.value, // 只获取当前志愿者的报名记录
      status: searchForm.status || undefined
    };
    
    // 修正API路径
    const response = await request.get('/signup-service/signup/list', { params });
    
    if (response.code === 200) {
      signupList.value = response.data.records || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '获取报名列表失败');
    }
  } catch (error) {
    ElMessage.error('获取报名列表失败，请重试');
    console.error('获取报名列表错误:', error);
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchSignupList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.activityId = '';
  searchForm.volunteerId = '';
  searchForm.status = '';
  currentPage.value = 1;
  fetchSignupList();
};

// 处理分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchSignupList();
};

// 处理当前页变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchSignupList();
};

// 打开新增报名对话框
const handleSignUp = () => {
  isEditMode.value = false;
  // 重置表单数据
  Object.assign(formData, {
    id: null,
    activityId: '',
    volunteerId: currentVolunteerId.value, // 自动填充当前志愿者ID
    status: 1
  });
  dialogVisible.value = true;
  
  // 重置表单验证
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate();
    }
  });
};

// 打开编辑报名对话框
const handleEditSignup = (row) => {
  isEditMode.value = true;
  // 复制数据到表单
  Object.assign(formData, {
    id: row.id,
    activityId: row.activityId,
    volunteerId: row.volunteerId,
    status: row.status
  });
  dialogVisible.value = true;
};

// 保存报名信息
const saveSignup = async () => {
  // 触发表单验证
  if (!formRef.value) return;
  
  const valid = await formRef.value.validate();
  if (!valid) return;
  
  try {
    let response;
    let successMessage;
    
    if (isEditMode.value) {
      // 编辑报名信息
      response = await request.post('/signup-service/signup/update', formData);
      successMessage = '报名信息更新成功';
    } else {
      // 新增报名
      response = await request.post('/signup-service/signup/add', {
        activityId: formData.activityId,
        volunteerId: formData.volunteerId // 使用当前志愿者ID
      });
      successMessage = '报名成功';
    }
    
    if (response.code === 200) {
      ElMessage.success(successMessage);
      dialogVisible.value = false;
      fetchSignupList();
    } else {
      ElMessage.error(response.message || (isEditMode.value ? '报名信息更新失败' : '报名失败'));
    }
  } catch (error) {
    ElMessage.error(isEditMode.value ? '报名信息更新失败，请重试' : '报名失败，请重试');
    console.error(isEditMode.value ? '更新报名信息错误' : '新增报名错误', error);
  }
};

// 处理删除报名
const handleDeleteSignup = (row) => {
  if (row.status !== 1) {
    ElMessage.warning('只能取消未签到的报名记录');
    return;
  }
  
  deleteSignupId.value = row.id;
  deleteDialogVisible.value = true;
};

// 确认删除报名
const confirmDelete = async () => {
  try {
    // 使用正确的变量名deleteSignupId
    const response = await request.post(`/signup-service/signup/delete?id=${deleteSignupId.value}`);
    
    if (response.code === 200) {
      ElMessage.success('报名记录取消成功');
      deleteDialogVisible.value = false;
      // 如果删除的是当前页最后一条数据，且不是第一页，则返回上一页
      if (signupList.value.length === 1 && currentPage.value > 1) {
        currentPage.value -= 1;
      }
      fetchSignupList();
    } else {
      ElMessage.error(response.message || '报名记录取消失败');
    }
  } catch (error) {
    ElMessage.error('报名记录取消失败，请重试');
    console.error('取消报名记录错误:', error);
  }
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  // 假设后端返回的是字符串格式的日期时间
  return dateTime.replace('T', ' ').substring(0, 19);
};

// 获取状态名称
const getStatusName = (status) => {
  const statuses = {
    1: '已报名',
    2: '已签到',
    3: '已签退',
    4: '已评价',
    5: '已取消'
  };
  return statuses[status] || '未知';
};

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    1: 'info',
    2: 'primary',
    3: 'warning',
    4: 'success',
    5: 'danger'
  };
  return types[status] || 'info';
};
</script>

<style scoped lang="scss">
.signup-management-container {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-top: 10px;
}

.table-card {
  min-height: 500px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.warning-text {
  color: #ff4d4f;
  margin-top: 10px;
}

/* 对话框样式调整 */
.el-dialog__body {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 18px;
}

/* 禁用按钮样式 */
.el-button:disabled {
  cursor: not-allowed;
  opacity: 0.6;
}
</style>    